package com.wodan.zhongjinjicang.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.wodan.zhongjinjicang.common.exception.BusinessException;
import com.wodan.zhongjinjicang.common.utils.JavaSmsApi;
import com.wodan.zhongjinjicang.common.utils.JsonUtils;
import com.wodan.zhongjinjicang.common.utils.VerificationCode;
import com.wodan.zhongjinjicang.enums.BusinessErrorEnum;
import com.wodan.zhongjinjicang.enums.YesOrNoEnum;
import com.wodan.zhongjinjicang.frame.AbstractClientApiJsonBusinessMethodService;
import com.wodan.zhongjinjicang.mapper.VerificationMapper;
import com.wodan.zhongjinjicang.model.UserBean;
import com.wodan.zhongjinjicang.model.VerificationBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * 验证码发送
 */
@Service("validCodeSend")
public class SmsValidCodeSendService extends AbstractClientApiJsonBusinessMethodService {


    private static final String PHONE = "phone";

    @Autowired
    private VerificationMapper verificationDao;

    @Override
    protected JSONObject doExecute(JSONObject data, String sessionId) {
        UserBean userBean = JsonUtils.jsonToPojo(data.toJSONString(), UserBean.class);

        String randPwd;
        VerificationBean v = verificationDao.selectByPhone(userBean.getPhone());
        //手机号在数据库中没有有效的验证码
        if(v!=null){
            Calendar c = Calendar.getInstance();
            if(v.getExpireTime().before(c.getTime())){
                //如果验证码过期拒绝修改，并将过期记录设置为失效；
                verificationDao.updateCodeStatus(YesOrNoEnum.NO.getCode(),v.getId());
                int i = insertVerificateionByPhone(userBean.getPhone());
                if(i==0){
                    throw new BusinessException(BusinessErrorEnum.ERROR.getCode(), "验证码生成失败");
                }
                v = verificationDao.selectByPhone(userBean.getPhone());
                randPwd = v.getValidCode() ;
            }else{
                //如果验证码在有效期内，客户端不会调用，此处为了防止可能被重复调用的风险
                throw new BusinessException(BusinessErrorEnum.ERROR.getCode(), "禁止重复调用接口");
            }
        }else{
            int i = insertVerificateionByPhone(userBean.getPhone());
            if(i==0){
                throw new BusinessException(BusinessErrorEnum.ERROR.getCode(), "验证码生成失败");
            }
            v = verificationDao.selectByPhone(userBean.getPhone());
            randPwd = v.getValidCode() ;
        }
        return sendMessage(userBean.getPhone(), randPwd);
    }

    public int insertVerificateionByPhone(String phone){
        VerificationBean record = new  VerificationBean();
        record.setValidCode(VerificationCode.createCode(true, 6));
        Calendar c = Calendar.getInstance();
        record.setCreateTime(c.getTime());
        c.add(Calendar.MINUTE, 1);
        record.setExpireTime(c.getTime());
        record.setPhone(phone);
        record.setExpire(YesOrNoEnum.YES.getCode());
        return verificationDao.insertSelective(record);
    }

    private JSONObject sendMessage(String phone, String randPwd) {
        try {
            String tpl_value = URLEncoder.encode("#code#","UTF-8") +"="
                    + URLEncoder.encode(randPwd, "UTF-8") ;
            //下发短信
            JavaSmsApi.tplSendSms(1121447, tpl_value, phone) ;
        } catch (IOException e) {
            throw new BusinessException(BusinessErrorEnum.ERROR.getCode(), "短信下发失败");
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("randPwd", randPwd);
        return new JSONObject(map);
    }


	@Override
	protected boolean isNeedLogin() {
		return false;
	}

    @Override
    protected String[] getRequiredParams() {
        return new String[]{PHONE};
    }

}
